package com.servlet;

import com.bean.Class;
import com.google.gson.Gson;
import com.service.ClassService;
import com.service.impl.ClassServiceImpl;
import com.utils.Page;
import com.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.utils.Page.PAGE_SIZE;

@WebServlet(name = "ClassServlet", urlPatterns = "/ClassServlet.do")
public class ClassServlet extends BaseServlet {
    ClassService classService = new ClassServiceImpl();

    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Class> list = classService.list();
        response.getWriter().write(WebUtils.parseJson(list));
    }

    protected void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), PAGE_SIZE);
        String content = request.getParameter("content");
        Page<Class> page = classService.page(pageNo, pageSize, content);
        Map map = new LinkedHashMap();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getPageTotalCount());
        map.put("data", page.getItems());

        response.getWriter().write(WebUtils.parseJson(map));
    }

    protected void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        int tip = classService.deleteById(id);
        String jsonStr = String.valueOf(tip);
        response.getWriter().write(jsonStr);
    }

    protected void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Class aClass = new Class();
        WebUtils.copyParamToBean(request.getParameterMap(), aClass);
        int tip = classService.updeteInfo(aClass);
        String jsonStr = String.valueOf(tip);
        response.getWriter().write(jsonStr);
    }

    protected void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Class aClass = new Class();
        WebUtils.copyParamToBean(request.getParameterMap(), aClass);
        aClass.setId(null);
        int tip = classService.insert(aClass);
        String jsonStr = String.valueOf(tip);
        response.getWriter().write(jsonStr);
    }

}
